package com.rc.fragment;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.rc.activity.DashBoardScreen;
import com.rc.activity.LoadData;
import com.rc.activity.R;
import com.rc.activity.ReceiptBox;
import com.rc.activity.ReceiptBox.OnBackPressedListener;
import com.rc.activity.ReceiptBox.OnOpenSliding;
import com.rc.activity.TripCreateNew;
import com.rc.activity.dao.tbl_Trip;
import com.rc.activity.dao.tbl_TripDao;
import com.rc.activity.provider.Contract;
import com.rc.adapter.DialogAdapter;
import com.rc.adapter.TripListAdapter;
import com.rc.db.DatabaseSupport;
import com.rc.util.SharedObjects;
import com.rc.util.Util;
import com.telpoo.frame.model.BaseModel;
import com.telpoo.frame.ui.BaseFragment;
import com.telpoo.frame.utils.Utils;

@SuppressLint({ "ValidFragment", "DefaultLocale" })
public class TripFragment extends BaseFragment implements OnClickListener,
		TextWatcher, OnBackPressedListener, OnOpenSliding {
	public static final String ACTION = "com.rc.trip";
	public TextView txtSearch;
	private View v = null;
	private RelativeLayout rlDateFilter, rlSelect, rlAllTrip;
	private Dialog dialog;
	private com.rc.custom.PullToRefreshListView lvTrip;
	private TripListAdapter adpTripList;
	private TextView txtSelect, txtAllTrip, txtEndDialog, txtStartDialog,
			txtTitle, txtContent, txtStart, txtEnd, txtDash;
	private ImageView imgAllTrip;
	private LinearLayout llAction, llFuntion, llActionCancel, llSearch,
			llFuntionSearch, llAddNew, llContent, llSearchbtCancel, llDelete;
	private ArrayList<tbl_Trip> arrTripObj;
	private String mIsStart = "";
	private boolean isCheck = true;
	private DatePicker dialog_datepicker;
	private int start = 0;
	private int end = 0;
	private String mTripType = "";
	private View loadMoreView;
	private MyReceiver myReceiver;
	private boolean myTripReceiverIsRegistered = false;
	private TripUpdateBroadcast tripBroadcast;

	public TripFragment(String mTripType, int start, int end) {
		super();
		this.mTripType = mTripType;
		this.start = start;
		this.end = end;
	}

	public TripFragment() {
		super();
	}

	@Override
	public void onStart() {
		// Register BroadcastReceiver
		// to receive event from our service
		myReceiver = new MyReceiver();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(ACTION);
		SharedObjects.context.registerReceiver(myReceiver, intentFilter);

		super.onStart();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onStop() {
		SharedObjects.context.unregisterReceiver(myReceiver);
		super.onStop();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		v = (ViewGroup) inflater.inflate(R.layout.triplist, null);
		((ReceiptBox) getActivity()).setTitle(getString(R.string.trip_list));
		((ReceiptBox) getActivity()).setLogo(R.drawable.ic_top_travelexpense);
		((ReceiptBox) getActivity()).setBackground(
				R.color.background_title_trip, getResources());
		((ReceiptBox) getActivity()).setOnBackPressedListener(new TripFragment(
				mTripType, start, end));
		((ReceiptBox) getActivity()).setOnOpenSliding(new TripFragment(
				mTripType, start, end));

		llAddNew = (LinearLayout) v.findViewById(R.id.llAddNew);
		rlDateFilter = (RelativeLayout) v.findViewById(R.id.rlDateFilter);
		rlSelect = (RelativeLayout) v.findViewById(R.id.rlSelect);
		lvTrip = (com.rc.custom.PullToRefreshListView) v
				.findViewById(R.id.PullToRefresh);
		txtSelect = (TextView) v.findViewById(R.id.txtSelect);
		imgAllTrip = (ImageView) v.findViewById(R.id.imgAllTrip);
		llAction = (LinearLayout) v.findViewById(R.id.llAction);
		llFuntion = (LinearLayout) v.findViewById(R.id.llFuntion);
		llActionCancel = (LinearLayout) v.findViewById(R.id.llActionCancel);
		llSearch = (LinearLayout) v.findViewById(R.id.llSearch);
		llFuntionSearch = (LinearLayout) v.findViewById(R.id.llFuntionSearch);
		llDelete = (LinearLayout) v.findViewById(R.id.llDelete);
		llSearchbtCancel = (LinearLayout) v.findViewById(R.id.llSearchbtCancel);
		rlAllTrip = (RelativeLayout) v.findViewById(R.id.rlAllTrip);
		txtAllTrip = (TextView) v.findViewById(R.id.txtAllTrip);
		txtContent = (TextView) v.findViewById(R.id.txtContent);
		txtSearch = (TextView) v.findViewById(R.id.txtSearch);
		txtStart = (TextView) v.findViewById(R.id.txtStart);
		txtEnd = (TextView) v.findViewById(R.id.txtEnd);
		txtDash = (TextView) v.findViewById(R.id.txtDash);

		rlAllTrip.setOnClickListener(this);
		rlDateFilter.setOnClickListener(this);
		rlSelect.setOnClickListener(this);
		llActionCancel.setOnClickListener(this);
		llAddNew.setOnClickListener(this);
		llSearch.setOnClickListener(this);
		llFuntionSearch.setOnClickListener(this);
		llDelete.setOnClickListener(this);
		llSearchbtCancel.setOnClickListener(this);
		txtSearch.addTextChangedListener(this);
		tripBroadcast = new TripUpdateBroadcast();

		return v;
	}

	@Override
	public void onResume() {
		super.onResume();

		if (!myTripReceiverIsRegistered) {
			getActivity().registerReceiver(tripBroadcast,
					new IntentFilter("update.trip"));
			myTripReceiverIsRegistered = true;
		}

		txtStart.setText(getString(R.string.all_date));
		arrTripObj = new ArrayList<tbl_Trip>();
		arrTripObj = DatabaseSupport.getTripByTripType(start, end, mTripType,
				getActivity());
		adpTripList = new TripListAdapter(mTripType, getActivity(), arrTripObj,
				start, end);
		if (arrTripObj.size() > 0 && lvTrip.getFooterViewsCount() == 0) {
			loadMoreView = ((LayoutInflater) getActivity().getSystemService(
					Context.LAYOUT_INFLATER_SERVICE)).inflate(
					R.layout.main_loadmore, null, false);
			lvTrip.addFooterView(loadMoreView);
			loadMoreView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					LoadData.callIntemt(getActivity(), 2);
				}
			});
		}
		lvTrip.setAdapter(adpTripList);
		txtAllTrip.setText(mTripType);
		txtContent.setText(mTripType);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.llFuntionSearch:
			llSearch.setVisibility(View.VISIBLE);
			llFuntion.setVisibility(View.GONE);
			break;
		case R.id.llDelete:
			createdialogDelete();
			break;
		case R.id.llAddNew:
			TripCreateNew.callIntent(getActivity());
			break;
		case R.id.rlDateFilter:
			createDialogDateFilter();
			break;
		case R.id.btDialogCancel:
			if (dialog != null) {
				if (dialog_datepicker.getVisibility() == View.GONE) {
					dialog.dismiss();
				} else {
					visibilityDateTimeDialog(false, "");
				}
			}
			break;
		case R.id.rlAllTrip:
			createDialogFilterTrip();
			break;
		case R.id.llActionCancel:
			displayFuntionBarBottom();
			break;
		case R.id.txtStarts:
			visibilityDateTimeDialog(true, "0");
			break;
		case R.id.txtEnds:
			visibilityDateTimeDialog(true, "1");
			break;
		case R.id.rlSelect:
			visiableSelect(!adpTripList.isShowCheck);
			break;
		case R.id.llSearchbtCancel:
			cancelAction();
			break;
		default:
			break;
		}
	}

	private void cancelAction() {
		displayFuntionBarBottom();
		txtSelect.setText(getString(R.string.select));
		llSearch.setVisibility(View.GONE);
		llFuntion.setVisibility(View.VISIBLE);
		Utils.hideKeyboard(getActivity(), (EditText) txtSearch);
		for (tbl_Trip objTrip : arrTripObj) {
			objTrip.setCheck(false);
		}
		adpTripList.notiB(arrTripObj, mTripType, start, end);
	}

	private void visibilityDateTimeDialog(boolean isEnable, String isStart) {
		if (isEnable) {
			dialog_datepicker.setVisibility(View.VISIBLE);
			llContent.setVisibility(View.GONE);
			txtTitle.setText(getString(R.string.choose_calendar));
			mIsStart = isStart;
		} else {
			String date_choose = Util
					.getDateByDateTimePicker(dialog_datepicker);
			if ("0".equals(mIsStart)) {
				txtStartDialog.setText(date_choose);
			} else {
				txtEndDialog.setText(date_choose);
			}
			mIsStart = "";
			dialog_datepicker.setVisibility(View.GONE);
			llContent.setVisibility(View.VISIBLE);
			txtTitle.setText(getString(R.string.date_filter));
		}
	}

	@SuppressLint("NewApi")
	private void createDialogDateFilter() {
		dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_trip_datefilter);

		Button btCancel, btOK;
		llContent = (LinearLayout) dialog.findViewById(R.id.llContent);
		btCancel = (Button) dialog.findViewById(R.id.btDialogCancel);
		btOK = (Button) dialog.findViewById(R.id.btOK);
		txtEndDialog = (TextView) dialog.findViewById(R.id.txtEnds);
		txtStartDialog = (TextView) dialog.findViewById(R.id.txtStarts);
		txtTitle = (TextView) dialog.findViewById(R.id.txtTitle);
		if (txtStart.getText().toString().equals(getString(R.string.all_date))) {
			txtStartDialog.setEnabled(false);
			txtEndDialog.setEnabled(false);
		} else {

		}

		final Switch mSwitch = (Switch) dialog.findViewById(R.id.swAllDate);
		mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (isChecked) {
					txtStartDialog.setEnabled(false);
					txtEndDialog.setEnabled(false);
				} else {
					txtStartDialog.setEnabled(true);
					txtEndDialog.setEnabled(true);
				}
			}
		});
		dialog_datepicker = (DatePicker) dialog
				.findViewById(R.id.dialog_datepicker);
		dialog.show();

		btCancel.setOnClickListener(this);
		btOK.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (dialog != null) {
					if (dialog_datepicker.getVisibility() == View.GONE) {

						if (mSwitch.isChecked()) {
							start = 0;
							end = 0;
							txtStart.setText(getString(R.string.all_date));
							txtDash.setVisibility(View.GONE);
							txtEnd.setText("");
							arrTripObj = new ArrayList<tbl_Trip>();
							arrTripObj = DatabaseSupport.getTripByTripType(
									start, end, mTripType, getActivity());
							adpTripList
									.notiB(arrTripObj, mTripType, start, end);
							dialog.dismiss();
						} else {
							String startString = txtStartDialog.getText()
									.toString();
							startString = startString.replace("/", "-");
							String endString = txtEndDialog.getText()
									.toString();
							endString = endString.replace("/", "-");
							if (Util.parseDateForInt(startString) <= Util
									.parseDateForInt(endString)) {
								start = Util.parseDateForInt(startString);
								end = Util.parseDateForInt(endString);
								arrTripObj = DatabaseSupport.getTripByTripType(
										start, end, mTripType, getActivity());
								adpTripList.notiB(arrTripObj, mTripType, start,
										end);
								txtStart.setText(txtStartDialog.getText()
										.toString());
								txtEnd.setText(txtEndDialog.getText()
										.toString());
								txtDash.setVisibility(View.VISIBLE);
								dialog.dismiss();
							}

						}
					} else {
						visibilityDateTimeDialog(false, "");
					}

				}
			}
		});
		;
		txtEndDialog.setOnClickListener(this);
		txtStartDialog.setOnClickListener(this);
		txtEndDialog.setText(Util.getDefaultInfor());
		txtStartDialog.setText(Util.getDefaultInfor());
	}

	private void visiableSelect(boolean mIsSelect) {
		if (mIsSelect) {
			llAction.setVisibility(View.VISIBLE);
			llFuntion.setVisibility(View.GONE);
			adpTripList.isShowCheck = true;
			isCheck = false;
			imgAllTrip.setImageResource(R.drawable.ic_selectitem);
			txtSelect.setText(getString(R.string.select_all));
			adpTripList.notifyDataSetChanged();

		} else {
			setImgSelect(isCheck);
		}

	}

	private void createDialogFilterTrip() {
		dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_receipt_choosetime);
		((TextView) dialog.findViewById(R.id.txtTitle))
				.setText(getString(R.string.filter_trips_by_type));
		final ListView lvDialog = (ListView) dialog.findViewById(R.id.lvDialog);
		DialogAdapter adpDialog = new DialogAdapter(getActivity(),
				DatabaseSupport.getArrTripTypes(getResources(), getActivity()),
				txtAllTrip.getText().toString());
		lvDialog.setAdapter(adpDialog);
		lvDialog.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				mTripType = ((TextView) lvDialog.getChildAt(position)
						.findViewById(R.id.txtTextDialog)).getText().toString();
				txtAllTrip.setText(mTripType);
				arrTripObj = new ArrayList<tbl_Trip>();
				arrTripObj = DatabaseSupport.getTripByTripType(start, end,
						mTripType, getActivity());
				adpTripList.notiB(arrTripObj, mTripType, start, end);
				txtContent.setText(mTripType);
			}
		});
		dialog.show();
	}

	public void toggleCheck(Boolean val) {
		for (int i = 0; i < lvTrip.getChildCount(); i++) {
			CheckBox cbMulti = null;
			cbMulti = (CheckBox) lvTrip.getChildAt(i)
					.findViewById(R.id.cbMulti);
			if (cbMulti != null)
				cbMulti.setChecked(val);
		}
	}

	private void setImgSelect(boolean isSelect) {
		toggleCheck(!isSelect);
		if (isSelect) {
			imgAllTrip.setImageResource(R.drawable.ic_selectitem);
			txtSelect.setText(getString(R.string.select_all));
			isCheck = false;
			for (tbl_Trip objTrip : arrTripObj) {
				objTrip.setCheck(false);
			}
		} else {
			imgAllTrip.setImageResource(R.drawable.ic_selectall);
			txtSelect.setText(getString(R.string.unselect_all));
			isCheck = true;
			for (tbl_Trip objTrip : arrTripObj) {
				objTrip.setCheck(true);
			}
		}

	}

	private void createdialogDelete() {
		dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_message);
		((TextView) dialog.findViewById(R.id.txtTitle))
				.setText(getString(R.string.delete_trip));
		((TextView) dialog.findViewById(R.id.txtContent))
				.setText(getString(R.string.are_you_sure_you_want_to_delete_selected_trip));
		((LinearLayout) dialog.findViewById(R.id.llCancel))
				.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});
		((LinearLayout) dialog.findViewById(R.id.llOk))
				.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						deleteMulti();
						cancelAction();
						dialog.dismiss();
					}
				});
		dialog.show();
	}

	private void displayFuntionBarBottom() {
		txtSelect.setText(getString(R.string.select));
		imgAllTrip.setImageResource(R.drawable.ic_selectitem);
		llAction.setVisibility(View.GONE);
		llFuntion.setVisibility(View.VISIBLE);
		adpTripList.isShowCheck = false;
		adpTripList.notifyDataSetChanged();
		toggleCheck(adpTripList.isShowCheck);
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {

	}

	private void deleteMulti() {
		boolean faill = false;
		for (tbl_Trip objTrip : arrTripObj) {
			if (objTrip.isCheck()) {
				objTrip.setIsDelete("1");
				if (DatabaseSupport.check_editTrip(objTrip.getTripID(),
						getActivity())) {
					if (getActivity().getContentResolver().update(
							Contract.CONTENT_URI_TRIP,
							objTrip.getContentValues(),
							tbl_TripDao.Properties.TripID.columnName + " = "
									+ objTrip.getTripID(), null) == -1) {
						faill = true;
					} else {
						faill = false;
					}
				} else {
					faill = true;
				}
			}
		}
		if (faill) {
			createDialogDeleteError();
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		if (myTripReceiverIsRegistered) {
			getActivity().unregisterReceiver(tripBroadcast);
			myTripReceiverIsRegistered = false;
		}
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if (txtSearch.getText().toString().length() > 0) {
			adpTripList.notiB(
					searchListView(arrTripObj, txtSearch.getText().toString()),
					mTripType, start, end);
		} else {
			if (adpTripList != null) {
				adpTripList.notiB(arrTripObj, mTripType, start, end);
			}
		}
	}

	public ArrayList<tbl_Trip> searchListView(ArrayList<tbl_Trip> arrTripObj,
			String contentSearch) {
		ArrayList<tbl_Trip> mArrTripList = new ArrayList<tbl_Trip>();
		for (int i = 0; i < arrTripObj.size(); i++) {
			if (arrTripObj.get(i).getName().toUpperCase()
					.contains(contentSearch.toUpperCase())) {
				mArrTripList.add(arrTripObj.get(i));
			}

		}
		return mArrTripList;
	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBack(Activity at) {
		DashBoardScreen.callIntent(at);
	}

	private void createDialogDeleteError() {
		final Dialog dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_message);

		LinearLayout llOk, llCancel;
		((TextView) dialog.findViewById(R.id.txtTitle)).setText(getActivity()
				.getString(R.string.error_deleting_trip));
		((TextView) dialog.findViewById(R.id.txtContent))
				.setText(getActivity()
						.getString(
								R.string.can_delete_trip_belonged_to_a_submitted_report));
		llOk = (LinearLayout) dialog.findViewById(R.id.llOk);

		llCancel = (LinearLayout) dialog.findViewById(R.id.llCancel);
		llCancel.setVisibility(View.GONE);
		llOk.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		dialog.show();

	}

	/**
	 * 
	 */
	private class MyReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			adpTripList.notiB(DatabaseSupport.getTripByTripType(start, end,
					mTripType, getActivity()), mTripType, start, end);
		}
	}

	/**
	 * Get BaseModel
	 */

	protected BaseModel getModel() {
		return ((ReceiptBox) getActivity()).model;
	}

	@Override
	public void doOpen(Activity at) {
		Util.HidenKeyBoard(at);
	}

	private class TripUpdateBroadcast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Log.e("push-update-trip", "1");
			arrTripObj = new ArrayList<tbl_Trip>();
			arrTripObj = DatabaseSupport.getTripByTripType(start, end,
					mTripType, getActivity());
			if (arrTripObj == null) {
				return;
			}
			adpTripList.notiB(arrTripObj, mTripType, start, end);
		}

	}
}
